<template>
  <div class="container sigin-container">
    <div class="body">
      <Spin v-show="loading" fix/>
      <div class="left">
        <div class="title">
          <span>签到<span class="color-orange">礼</span>包</span>
          <div @click="showRule = true">签到规则<i class="iconfont icon-arrow1"/></div>
        </div>
        <div class="data-card">
          <div class="flex col-center row-between">
            <div class="fz-16">今日倒计时</div>
            <div class="total-time">已签到<span class="time">{{ signData.signNum }}</span>天</div>
          </div>
          <div class="time-info">
            <div class="time-down">
              <div class="time">{{ signTime }}</div>
              <div class="fz-16">{{todayStatus ==  2 ? '今日已签到': '后可签到'}}</div>
            </div>
          </div>
          <div class="cell-group">
            <div class="cell">
              <div>
                <img src="@/assets/images/signIn/icon-on.png" alt=""/>已上机
              </div>
              <div><span class="val">{{ onlineTime[0] }}</span>{{ onlineTime[1] }}</div>
            </div>
            <div class="cell">
              <span class="iconfont icon-youjiantou arrow"/>
              <div v-if="signData.fillType == 2">今日已补签</div>
              <template v-else>
               <div>
                 <img src="@/assets/images/signIn/icon-buqian.png" alt=""/><span class="fz-18">{{ fillTime }}</span>后可补签
               </div>
               <div><span class="val">1</span>次</div>
              </template>
            </div>
          </div>
        </div>
        <router-link to="/sigIn/record" class="record-btn" v-show="memberInfo">签到领取记录<i class="iconfont icon-arrow1"/></router-link>
        <div class="total-cell">
          <div :class="['item', item.statusLabel, (item.gift ? 'gift-'+item.gift.type : 'no-gift')]"
               v-for="(item, index) in cycleList"
               @click="giveGift(item)"
          >
            <span class="checked" v-if="item.status == 2"><span class="iconfont icon-gou"/></span>
            <div class="name">{{item.gift ? item.gift.name: '' }}</div>
            <div class="desc">累计签到{{ item.days }}天</div>
          </div>
        </div>
      </div>
      <div class="right">
        <div class="week-list">
          <div class="item" v-for="(i,k) in weekList" :key="'b'+k">{{i}}</div>
        </div>
        <div class="day-body">
          <div class="day-list">
            <div class="item" v-for="(i,k) in beforeDays" :key="'b'+k"></div>
            <div :class="['item day', item.statusLabel]"
                 v-for="(item,index) in dayList"
                 :key="item.days"
                 :ref="`day${index}`"
                 @mouseenter="dayHover(item, index, true)"
                 @mouseleave="dayHover(item, index, false)"
                 @click="signIn(item, index)">
              <span class="num"><span>{{ item.days < 10 ? '0'+item.days : item.days }}</span>天</span>
              <div :class="['gift-con', (!item.gift ? 'no-gift' : 'gift-'+item.gift.type)]">
                <div class="gift-text" v-if="item.gift">
                  <span v-if="item.gift.type == 4">{{item.gift.name}}</span>
                  <div v-else>
                    <div>{{item.gift.money}}{{item.gift.label}}</div>
                    <div>{{awardName[item.gift.type]}}</div>
                  </div>
                </div>
              </div>
              <div class="bottom"></div>
            </div>
          </div>
        </div>
        <div class="day-tooltip" ref="dayTooltip" :style="dayTooltip.style">
          <div class="tooltip-con">
            <div class="title">签到奖励内容</div>
            <div class="item" v-for="(item, index) in dayTooltip.giftList">
              <img src="@/assets/images/signIn/icon-star.png" alt="">{{ item.name }}
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--规则弹窗-->
    <div class="rule-model" :class="{show: showRule}">
      <div class="rule-body">
        <div class="head">
          <img src="@/assets/images/icon-close.png" alt="" @click="showRule = false"/>
        </div>
        <div class="content">
          <p>1. 每日上机满<span class="color-brown bold">{{ signData.signMine }}</span>分钟即可签到一次，每日<span class="color-brown bold">0</span>点更新，每天仅限一次，不可重复签到。
          </p>
          <p>2. 签到按月份循环，每月奖励有所不同。</p>
          <p>3. 已累积签到是连续记录，循环结束不会重置累积总签到天数。</p>
          <p>4. 可跨门店签到，在电竞蜂旗下门店签到不会断签影响连续签到。</p>
          <p>5. 签到成功后奖励会自动发放到个人卡包，优惠券请在有效期之内使用。</p>
          <p>6. 上机满<span class="color-brown bold">{{ signData.fillSignMine }}</span>分钟即可补签，每天可补签一次，补签成功会累积签到天数。</p>
          <p>7. 每月累积签到达到<span class="color-brown bold">{{ signDays }}</span>即可领取对应礼包，当月结束后会重置礼包。</p>
        </div>
      </div>
    </div>
    <!--奖励领取弹窗-->
    <div class="award-model" :class="{show: showAward}">
      <div class="model-body">
        <div class="award-head">
          <div class="title">恭喜您获得</div>
          <div class="sub">签到奖励</div>
          <img src="@/assets/images/icon-close.png" alt="" @click="showAward = false"/>
        </div>
        <div class="award-body">
          <div class="exit-img"></div>
          <div class="award-list">
            <div class="item" v-for="(item, index) in awardList" :key="index">
              <template v-if="item.type == 1">
                <div class="value"><span>{{item.rate}}</span>折</div>
                <div class="content">饮品券</div>
              </template>
              <template v-else>
                <div class="value"><span>{{item.type == 4 ? 0 : item.presenterMoney}}</span>元</div>
                <div class="content">{{awardName[item.type]}}</div>
              </template>
            </div>
          </div>
        </div>
        <div class="award-footer"/>
      </div>
    </div>
  </div>
</template>
<script>
import {mapGetters, mapState} from "vuex";
import {saveCycle, signIn, signInList, signRankingList} from "@/api/signIn";
import {dateDiff, dateDiff1, nameStar, timingDown} from "@/common/utils";
import {getMemberInfo} from "@/api/member";
import {decryptByDESModeCBC} from "@/common/utils/des";

export default {
  name: "index",
  data() {
    return {
      memberInfo: null,
      beforeDays: 0,
      onlineTime: [0, '小时'],
      signTime: '00:00',
      fillTime: '00:00',
      signData: {
        fillSignMine: 0, // 补签时间
        fillType: 1, // 今日是否补签 1:未补签  2:已补签
        signMine: 3, // 签到时间(分钟)
        signNum: 0, // 当月累计签到次数
      },
      todayStatus: 1, // 今天签到状态 1:未签到 2:已签到
      cycleList: [],
      dayList: [],
      weekList: ['一', '二', '三', '四', '五', '六', '日'],
      dayTooltip: {
        giftList: [],
        style: {
          active: -1,
          top: '-1000px',
          left: '-1000px'
        }
      },
      rankingList: [],
      rankingMy: {
        totalNum: 0
      },
      showRule: false,
      showAward: false,
      awardList: [],
      awardName: {
        1: '饮品券',
        2: '充送券',
        3: '网费',
        4: '包时卡'
      },
      loading: false,
      saveLoading: false
    };
  },
  computed: {
    ...mapGetters(['shop', 'shopId', 'themeName']),
    progress() {
      let list = JSON.parse(JSON.stringify(this.cycleList));
      list = list.sort()
      let max = 0
      for (const k in list) {
        let item = list[k]
        if (this.signData.signNum >= item.days) {
          max = k
        }
      }
      return Math.min(Math.max(max, 0) * 200, 400)
    },
    signDays() {
      let day = this.cycleList.map(item => item.days + '天')
      return day.join('、')
    },
  },
  mounted() {
    let currentDate = new Date();
    currentDate.setDate(1);
    let dayOfWeek = currentDate.getDay();
    dayOfWeek = dayOfWeek == 0 ? 7 : dayOfWeek
    this.beforeDays = dayOfWeek - 1
  },
  methods: {
    async init() {
      this.cycleList = this.dayList = []
      clearTimeout(this.inter || null)
      if (!this.shopId) {
        this.$Message.error("会员信息异常!")
        return
      }
      this.loading = true
      let memberInfoRes = await getMemberInfo()
      if (!memberInfoRes || memberInfoRes.code != 200) {
        this.$Message.error("会员信息异常")
        return
      }
      this.memberInfo = JSON.parse(decryptByDESModeCBC(memberInfoRes.msg))
      let signInfoRes = await signInList({lgUserId: this.memberInfo.memberId})
      if (!signInfoRes || !signInfoRes.data) {
        this.loading = false
        this.$Message.error("签到活动维护中")
        return
      }
      this.loading = false
      signInfoRes = signInfoRes.data
      this.signData = signInfoRes
      this.onlineDownTime(signInfoRes.currTime)
      let today = new Date()
      this.cycleList = signInfoRes.cycleList.map(cycle => {
        cycle.statusLabel = cycle.status == 1 && signInfoRes.signNum >= parseInt(cycle.days) ? 'normal': 'disabled'
        if (cycle.giftList) {
          cycle.giftList = JSON.parse(cycle.giftList)
          cycle.giftList = this.formatGift(cycle.giftList)
          cycle.gift = cycle.giftList[0] || null
        }
        return cycle
      })
      this.dayList = signInfoRes.dayList.map(day => {
        day.statusLabel = 'disabled'
        if (day.giftList) {
          day.giftList = JSON.parse(day.giftList)
          day.giftList = this.formatGift(day.giftList)
          day.gift = day.giftList[0] || null
        }
        if (day.days == today.getDate()) {
          this.todayStatus = day.status
        }
        return day
      })
      this.dayTimeDown(signInfoRes.currTime)
    },
    formatGift(giftList) {
      return giftList.map(gift => {
        gift.label = ''
        gift.money = ''
        if (gift.type == 1) {
          gift.rate = parseInt(gift.rate / 10)
          gift.label = '折'
          gift.money = gift.rate
          gift.name = gift.rate + '折饮品券'
        } else if (gift.type == 2) {
          gift.label = '元'
          gift.name = gift.conditionMoney + '元充送券'
          gift.money = gift.conditionMoney
        } else if (gift.type == 3) {
          gift.label = '元'
          gift.name = gift.presenterMoney + '元网费'
          gift.money = gift.presenterMoney
        }
        return gift
      })
    },
    onlineDownTime(curTime) {
      var date1 = new Date(this.memberInfo.onlineTime)
      var date2 = new Date(curTime)
      var diffTime = Math.abs(date2 - date1) // 时间差的毫秒数
      const minutes = Math.floor(diffTime / (1000 * 60));
      const hours = Math.floor(diffTime / (1000 * 60 * 60));
      if (hours > 0) {
        this.onlineTime = [hours, '小时']
      } else {
        this.onlineTime = [minutes, '分钟']
      }
      clearTimeout(this.inter || null)
      this.inter = setInterval(() => {
        curTime += 1000
        this.onlineDownTime(curTime);
      }, 1000);
    },
    dayTimeDown(currTime) {
      clearTimeout(this.timing || null)
      this.signTime = '00:00'
      this.fillTime = '00:00'
      let time = currTime / 1000
      let diffTime = parseInt((time - this.memberInfo.onlineTime / 1000) / 60)
      const signDay = this.dayList.find(item => item.status == 3)
      const fillDay = this.dayList.find(item => item.status == 4 && this.signData.fillType == 1)
      if (signDay) {
        let signMaxTime = this.signData.signMine
        if (diffTime < signMaxTime) {
          let signTime = parseInt(this.memberInfo.onlineTime / 1000 + signMaxTime * 60) * 1000
          signTime = timingDown(signTime)
          this.signTime = parseInt(signTime.replace(':', '')) == 0 ? '00:00' : signTime
        }
      }
      if (fillDay){
        let fillMaxTime = this.signData.fillSignMine
        if (diffTime < fillMaxTime) {
          let fillTime = parseInt(this.memberInfo.onlineTime / 1000 + fillMaxTime * 60) * 1000
          fillTime = timingDown(fillTime)
          this.fillTime = parseInt(fillTime.replace(':', '')) == 0 ? '00:00' : fillTime
        }
      }
      // 1:未签到  2:已签到  3.可以签到 4:可以补签
      let status = {
        1: 'disabled', // 不可签到
        2: 'end', // 已签到
        3: 'normal', // 可签到
        4: 'fill', // 可补签
      }
      this.dayList.map(day => {
        day.statusLabel = status[day.status]
        if (day.status == 3 && this.signTime == '00:00') { // 可签到
          day.statusLabel = status[day.status]
        }
        if (day.status == 4) {
          if (this.signData.fillType == 2) {
            day.statusLabel = 'disabled'
          } else if (this.fillTime == '00:00') { // 可补签
            day.statusLabel = status[day.status]
          }
        }
        return day
      })
      if (this.signTime != '00:00' || this.fillTime != '00:00') {
        this.timing = setTimeout(() => {
          this.dayTimeDown(currTime)
        }, 1000)
      }
    },
    daySignStatus(item) {
      if (item.time) return 'time'
      if (this.signData.fillType == 2 && item.status == 4) return 'disabled'
      return {
        1: 'disabled', // 不可签到
        2: 'end', // 已签到
        3: 'normal', // 可签到
        4: 'fill', // 可补签
      }[item.status]
    },
    dayHover(item, index, isEnter) {
      if (!item.giftList || !item.giftList.length) return
      if (!isEnter) {
        this.dayTooltip = {
          style: {
            active: -1,
            top: '-1000px',
            left: '-1000px'
          }
        }
      } else {
        let rect = this.$refs[`day${index}`][0].getBoundingClientRect();
        let { top, left,} = rect
        left = left - (48 / 2) + 2
        const dayTooltip = this.$refs.dayTooltip.getBoundingClientRect()
        let style = {
          top: `${top - dayTooltip.height - 12}px`,
          left: `${left}px`
        }
        this.dayTooltip = {
          giftList: item.giftList,
          style
        }
      }
    },

    // 签到
    signIn(data) {
      let status = this.daySignStatus(data);
      if (['fill', 'normal'].indexOf(status) == -1) return
      let params = {
        lgUserId: this.memberInfo.memberId,
        dayId: data.dayId,
        type: status == 'fill' ? 2 : 1,
        shopId: this.shop.shopId,
        signId: this.signData.id
      }
      if (this.saveLoading) return
      this.saveLoading = true
      signIn(params).then(res => {
        if (res.code != 200) {
          this.$Message.error(res.msg)
          return
        }
        this.$Message.success('签到成功')
        if (data.giftList && data.giftList.length) {
          this.awardList = data.giftList
          this.showAward = true
        }
        this.init()
        /*this.dayList.map(item => {
          if (item.days == data.days) {
            item.status = 2
          } else {
            if (params.type == 2 && item.status == 4) { // 补签
              item.status = 1
            }
          }
          item.statusLabel = this.daySignStatus(item)
          return item
        })
        this.signData.signNum += 1
        signRankingList({lgUserId: this.memberInfo.memberId}).then(rankingRes => {
          if (rankingRes.data) {
            this.rankingList = rankingRes.data.list || []
            this.rankingList.map(item => {
              item.userName = nameStar(item.userName)
            })
            this.rankingMy = rankingRes.data.mySign || {totalNum: 0}
          }
        })*/
      }).finally(() => {
        this.saveLoading = false
      })
    },
    // 领取累计奖励
    giveGift(item) {
      if (item.status == 2) return
      let params = {
        lgUserId: this.memberInfo.memberId,
        shopId: this.shop.shopId,
        signId: this.signData.id,
        cycleId: item.cycleId
      }
      saveCycle(params).then(res => {
        if (res.code != 200) {
          this.$Message.error(res.msg)
          return
        }
        if (item.giftList && item.giftList.length) {
          this.awardList = item.giftList
          this.showAward = true
        } else {
          this.$Message.error("没有可领取奖励")
        }
        item.status = 2
        item.statusLabel = 'disabled'
      })
    }
  },
  created() {
    this.init()
  },

  destroyed() {
    clearTimeout(this.timing)
  },
}
</script>

<style lang="scss">
@import "index.scss";
</style>
